package ink.xiaobaibai.advice;

import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @description: RequestBody接口实现类
 * @author: 小白白
 * @create: 2021-05-22
 **/

@RestControllerAdvice(basePackages = {"ink.xiaobaibai.controller"})
public class OxyRequestBodyAdvice implements RequestBodyAdvice {

    /**
     * @param methodParameter 方法
     * @param type            参数类型
     * @param aClass          转换器类型
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        //只负责String参数的@RequestBody方法
        return methodParameter.getParameterType() == String.class;
    }

    /**
     * 读取前操作
     *
     * @return
     * @throws IOException
     */
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return httpInputMessage;
    }

    /**
     * 读取后操作
     *
     * @return
     */
    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        String s = o.toString();
        if (s.lastIndexOf('=') == (s.length() - 1)) {
            s = s.substring(0, s.length() - 1);
        }
        return s;
    }

    /**
     * 空参数处理器
     *
     * @return
     */
    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

}
